/*
 * Copyright 2014-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wzq.util;

import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import net.sf.json.JSONObject;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 * 签名工具类
 * 
 * @ClassName: UtilSign
 * @date 2016年4月9日 上午10:26:40
 * @version v 1.0
 */
public class UtilSign {
	protected final static Logger logger = LogManager.getLogger(UtilSign.class);

	public static String sign(String signKey, Map<String, String[]> reqParamMap) {
		Map<String, String[]> paramsMap = reqParamMap instanceof TreeMap ? reqParamMap : new TreeMap<>(reqParamMap);
		StringBuilder buf = new StringBuilder(paramsMap.size() * 20);
		for (Entry<String, String[]> entry : paramsMap.entrySet()) {
			String key = entry.getKey();
			if ("sign".equals(key))
				continue;

			key = UtilString.encodeURL(key);
			for (String value : entry.getValue()) {
				buf.append(key).append('=').append(value).append('&');
			}
		}
		buf.append("key=").append(signKey);
		return UtilString.md5(buf.toString());
	}

	/**
	 * 对json数据进行签名
	 * 
	 * @author 陈剑飞
	 * @Title: signJson
	 * @param signKey
	 * @param json
	 * @Return: String 返回值
	 */
	public static boolean signJson(String signKey, String json, String requestUrl) {
		JSONObject jsonObj = JSONObject.fromObject(json);
		TreeMap<String, Object> params = UtilJson.convertValue(json, TreeMap.class);
		StringBuilder buf = new StringBuilder(params.size() * 20);
		String reqSign = "";
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			String key = entry.getKey();
			key = UtilString.encodeURL(key);
			String value = "";
			Object valueObj = entry.getValue();
			if (valueObj instanceof ArrayList || valueObj instanceof Map) {
				value = jsonObj.get(key).toString();
			} else {
				value = entry.getValue().toString();
			}
			if ("sign".equals(key)) {
				reqSign = value;
				continue;
			}
			buf.append(key).append('=').append(value).append('&');
		}
		buf.append("key=").append(signKey);
		logger.debug("签名字符串sign={}", buf.toString());
		if (UtilString.isEmpty(reqSign) || reqSign.length() != UtilString.md5Len) {
			logger.debug("签名错误 request.sign={}, url={}", reqSign, requestUrl);
			return false;
		}
		String sign = UtilString.md5(buf.toString());
		boolean result = sign.equalsIgnoreCase(reqSign);
		logger.debug("签名={}, request.sign={}, sign={}, url={}, params={}", result, reqSign, sign, requestUrl, params);
		return result;
	}
	
	/**  
     * 获取签名    
     * @author qianzq   
     * @Title: getSignByJson    
     * @param signKey
     * @param json
     * @Return: String 返回值  
     */
    public static String  getSignByJson(String json) {
        JSONObject jsonObj = JSONObject.fromObject(json);
        TreeMap<String, Object> params = UtilJson.convertValue(json, TreeMap.class);
        StringBuilder buf = new StringBuilder(params.size() * 20);
        String reqSign = "";
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            key = UtilString.encodeURL(key);
            String value = "";
            Object valueObj = entry.getValue();
            if (valueObj instanceof ArrayList || valueObj instanceof Map) {
                value = jsonObj.get(key).toString();
            } else {
                value = entry.getValue().toString();
            }
            if ("sign".equals(key)) {
                reqSign = value;
                continue;
            }
            buf.append(key).append('=').append(value).append('&');
        }
        buf.append("key=").append("219F223CB59B183D3A80708E8553AFA71b49");
        logger.info("签名字符串sign={}", buf.toString());
        String sign = UtilString.md5(buf.toString());
        return sign;
    }
	
}
